package com.xhl.oauth2.config.oauth2;

import com.xhl.oauth2.base.R;
import com.xhl.oauth2.base.constant.Oauth2Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity translate(Exception e) {
        ResponseEntity.BodyBuilder status = ResponseEntity.status(HttpStatus.UNAUTHORIZED);
        String message = Oauth2Constant.AUTHENTICATION_FAILED;
        log.info(message, e);
        if (e instanceof UnsupportedGrantTypeException) {
            message = Oauth2Constant.NOT_SUPPORTED_AUTHENTICATION_TYPE;
            return status.body(R.error(message + ":" + e.getMessage()));
        }
        if (e instanceof InvalidTokenException
                && StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token (expired)")) {
            message = Oauth2Constant.TOKEN_EXPIRATION;
            return status.body(R.error(message + ":" + e.getMessage()));
        }
        if (e instanceof InvalidScopeException) {
            message = Oauth2Constant.NOT_VALID_SCOPE;
            return status.body(R.error(message + ":" + e.getMessage()));
        }
        if (e instanceof InvalidGrantException) {
            if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) {
                message = Oauth2Constant.NOT_VALID_REFRESH_TOKEN;
                return status.body(R.error(message + ":" + e.getMessage()));
            }
            if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) {
                message =  Oauth2Constant.USER_LOCKED;
                return status.body(R.error(message + ":" + e.getMessage()));
            }
            message = Oauth2Constant.USER_OR_PASSWORD_WRONG;
            return status.body(R.error(message + ":" + e.getMessage()));
        }
        return status.body(R.error(message + ":" + e.getMessage()));
    }
}
